using UnityEngine;
using System.Collections.Generic;

public class UpgradesController : MonoBehaviour, ISaveController
{
    private const string SAVE_UNIQUE_IDENTIFIER = "upgrades";

    [SerializeField] UpgradesDatabase upgradesDatabase;

    private static BaseUpgrade[] activeUpgrades;
    public static BaseUpgrade[] ActiveUpgrades => activeUpgrades;

    private static Dictionary<UpgradeType, BaseUpgrade> activeUpgradesLink;

    public string UniqueSaveName => SAVE_UNIQUE_IDENTIFIER;

    private void OnEnable()
    {
        UpgradesEventsHandler.OnUpgraded += OnUpgraded;
    }

    private void OnDisable()
    {
        UpgradesEventsHandler.OnUpgraded -= OnUpgraded;
    }

    public void Initialise()
    {
        activeUpgrades = upgradesDatabase.Upgrades;

        activeUpgradesLink = new Dictionary<UpgradeType, BaseUpgrade>();
        for (int i = 0; i < activeUpgrades.Length; i++)
        {
            if (!activeUpgradesLink.ContainsKey(activeUpgrades[i].UpgradeType))
            {
                activeUpgrades[i].Initialise();

                activeUpgradesLink.Add(activeUpgrades[i].UpgradeType, activeUpgrades[i]);
            }
        }

        // Register save object
        SaveController.RegisterSaveObject(this);
    }

    public static BaseUpgrade GetUpgradeByType(UpgradeType perkType)
    {
        if (activeUpgradesLink.ContainsKey(perkType))
            return activeUpgradesLink[perkType];

        Debug.LogError($"[Perks]: Upgrade with type {perkType} isn't registered!");

        return null;
    }

    private void OnUpgraded(UpgradeType perkType, BaseUpgrade perk)
    {
        SaveController.MarkAsSaveIsRequired();
    }

    public void Load(ISaveObject saveObject)
    {
        // Check if save exists
        if (saveObject != null)
        {
            // Change save type
            UpgradesSave upgradesSave = (UpgradesSave)saveObject;
            if (upgradesSave != null)
            {
                for (int i = 0; i < upgradesSave.UpgradeSaves.Length; i++)
                {
                    for (int c = 0; c < activeUpgrades.Length; c++)
                    {
                        if (upgradesSave.UpgradeSaves[i].UpgradeType == activeUpgrades[c].UpgradeType)
                        {
                            activeUpgrades[c].Load(upgradesSave.UpgradeSaves[i]);

                            break;
                        }
                    }
                }
            }
        }
    }

    public ISaveObject Save()
    {
        return new UpgradesSave(activeUpgrades);
    }
}
